package zserver

import (
	"fmt"
	"net"
	"zinx/zinterface"
)

type Zserver struct {
	Name      string // 服务器名称
	IP        string // 监听地址
	Port      int    // 监听端口
	IPVersion string // 监听方法
}

func (z *Zserver) Start() {
	fmt.Printf("START SERVER '%s' on IP '%s:%d'", z.Name, z.IP, z.Port)

	go func() {
		// 获取socket
		tcpAddr, err := net.ResolveTCPAddr(z.IPVersion, fmt.Sprintf("%s:%d", z.IP, z.Port))
		if err != nil {
			fmt.Println("ERROR ON START SERVER :", err)
			return
		}

		// 开始监听
		listenner, err := net.ListenTCP(z.IPVersion, tcpAddr)
		if err != nil {
			fmt.Println("ERROR ON LISTENNING ADDR: ", err)
			return
		}

		// 阻塞地等待客户端连接，处理客户端业务
		for {
			conn, err := listenner.AcceptTCP()
			if err != nil {
				fmt.Println("ERROR ON ACCEPT CLIENT: ", err)
				continue
			}

			go func() {
				for {
					buf := make([]byte, 512)
					cnt, err := conn.Read(buf)
					if err != nil {
						fmt.Println("ERROR ON READ CLIENT: ", err)
						continue
					}

					fmt.Printf("Recieve from Client: %s, cnt: %d\n", buf, cnt)

					// 简单回显
					if _, err := conn.Write(buf[:cnt]); err != nil {
						fmt.Println("ERROR ON WRITE CLIENT: ", err)
						continue
					}

				}
			}()
		}
	}()

}

func (z *Zserver) Stop() {

}

func (z *Zserver) Serve() {
	z.Start()

	select {}
}

func New(name string) zinterface.Zinterface {
	zs := &Zserver{
		Name:      name,
		IP:        "0.0.0.0",
		Port:      8999,
		IPVersion: "tcp4",
	}

	return zs
}
